﻿using HCMS.Const;
using HCMS.Entities.Base;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Services;

namespace HCMS.DomainServiceManage.Cache.Base
{
    /// <summary>
    /// 敏感词 缓存 域服务
    /// </summary>
    public class SensitiveWordsCacheManager : DomainService
    {
        private readonly IDistributedCache cache;

        public SensitiveWordsCacheManager(IDistributedCache cache)
        {
            this.cache = cache;
        }

        /// <summary>
        /// 设置 列表 信息
        /// </summary>
        /// <param name="sensitiveWords">敏感词列表</param>
        /// <returns></returns>
        public async Task<bool> SetList(List<SensitiveWords> sensitiveWords)
        {
            if (sensitiveWords == null || !sensitiveWords.Any()) { return false; }

            string serializeValule = JsonConvert.SerializeObject(sensitiveWords);
            byte[] storeValue = Encoding.UTF8.GetBytes(serializeValule);
            DistributedCacheEntryOptions options = new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(6));
            await cache.SetAsync(Base_RedisKey.SensitiveWordsAllList, storeValue, options);

            return true;
        }

        /// <summary>
        /// 获取 列表 信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<SensitiveWords>> GetList()
        {
            string cacheValue = (await cache.GetStringAsync(Base_RedisKey.SensitiveWordsAllList)) ?? "";
            if (string.IsNullOrWhiteSpace(cacheValue))
            {
                return new List<SensitiveWords>();
            }

            var result = JsonConvert.DeserializeObject<List<SensitiveWords>>(cacheValue);
            return result ?? new List<SensitiveWords>();
        }
    }
}
